angular.module('webapp')
    .controller('NewsController',['$scope','NewsService', NewsController]);

function NewsController($scope,NewsService) {
    $scope.list = [];
    $scope.current = {};
    $scope.news = {};

    /**
     * 创建新闻
     */
    $scope.createNews = function(){
        $("#modal-editor").modal('show');
    }

    $scope.save = function(){
        if(!$scope.news.title){
            $scope.editorMessage = 'Title is required';
        }else if(!$scope.news.content){
            $scope.editorMessage = 'Content is required';
        }else{
            $scope.editorMessage = '';
            NewsService.save($scope.news).then(
                function(data){
                    $("#modal-editor").modal('hide');
                    $scope.loadNews();
                },
                function(err){
                    $scope.editorMessage = err;
                }
            );
        }
    }

    /**
     * 根据id展示相应的新闻详情
     * @param {*} id 
     */
    $scope.openNewsDetail = function (id) {
        console.log(id);
        $scope.loadNews(id);
        $("#modal-detail").modal('show');
    }

    /**
     * 格式化时间
     * @param {*} time 
     */
    $scope.formatTime = function (time) {
        return moment(time).format('YYYY-MM-DD');
    }

    /**
     * 加载新闻
     */
    $scope.loadNews = function (id) {
        if(id){
            console.info('根据id加载新闻详情',id);
            NewsService.detail(id).then(
                function (data) {
                    $scope.current = data;
                },
                function(err){
                    console.error(err);
                }
            );
        }else{
            console.info('加载新闻列表');
            NewsService.list().then(
                function(data){
                    $scope.list = data;
                },
                function(err){
                    console.log(err);
                }
            );
        }
    }

    $scope.loadNews();
}